package com.chart.chart.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chart.chart.domian.ChartOrders;
import com.chart.chart.mapper.ChartOrdersMapper;
import com.chart.chart.service.IChartOrdersService;
import com.chart.common.utils.SecurityUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class ChartOrdersServiceImpl extends ServiceImpl<ChartOrdersMapper, ChartOrders> implements IChartOrdersService {


    @Autowired
    private ChartOrdersMapper chartOrdersMapper;


    @Override
    public boolean updateOrderStatu(String orderNum) {
        return chartOrdersMapper.updateOrderStatu(orderNum);
    }



    @Override
    public List<ChartOrders> listOrdersSortedByCreateTime(int pageNum, int pageSize) {
        Long userId = SecurityUtils.getUserId();

        PageHelper.startPage(pageNum, pageSize);

        LambdaQueryWrapper<ChartOrders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChartOrders::getUserId, userId);
        queryWrapper.eq(ChartOrders::getStatus, 1);        // Filter by status (1 for paid)
        queryWrapper.orderByDesc(ChartOrders::getCreateTime); // Order by create time descending

        List<ChartOrders> ordersList = chartOrdersMapper.selectList(queryWrapper);

        for (ChartOrders order : ordersList) {
            // Convert totalPrice from cents to yuan
            if (order.getTotalPrice() != null) {
                BigDecimal priceInYuan = BigDecimal.valueOf(order.getTotalPrice())
                        .divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP);
                order.setTotalPriceInYuan(priceInYuan);
            }

            if (order.getInvoice() == null || order.getInvoice() == 0) {
                order.setInvoiceStatus("未开票");
            } else if (order.getInvoice() == 1) {
                order.setInvoiceStatus("已开票");
            }

            if (order.getStatus() != null) {
                order.setPaymentStatus(order.getStatus() == 0 ? "未支付" : "已支付"); // Payment status
            }
        }

        return ordersList;
    }





    @Override
    public PageInfo<ChartOrders> findPage(int page, int size, String phonenumber) {
        // 使用 PageHelper 开启分页
        PageHelper.startPage(page, size);

        // 调用 Mapper 方法执行 SQL 查询
        List<ChartOrders> ordersList = chartOrdersMapper.findUserOrders(phonenumber);

        // 使用 PageInfo 封装分页结果
        return new PageInfo<>(ordersList);
    }

    @Override
    public List<ChartOrders> queryOrder() {
        return chartOrdersMapper.queryOrder();
    }



    @Override
    public ResponseEntity<byte[]> exportOrdersToExcel() throws IOException {
        // 查询订单数据
        List<ChartOrders> chartOrdersList = queryOrder();

        // 设置发票状态
        for (ChartOrders chartOrders : chartOrdersList) {
            Integer invoice = chartOrders.getInvoice();
            if (invoice == null || invoice == 0) {
                chartOrders.setInvoiceStatus("未开票");
            } else if (invoice == 1) {
                chartOrders.setInvoiceStatus("已开票");
            }
        }

        // 创建 Excel 工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Orders");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("手机号");
        headerRow.createCell(1).setCellValue("订单号");
        headerRow.createCell(2).setCellValue("订单详情");
        headerRow.createCell(3).setCellValue("订单时间");
        headerRow.createCell(4).setCellValue("金额");
        headerRow.createCell(5).setCellValue("发票");

        // 填充数据
        for (int i = 0; i < chartOrdersList.size(); i++) {
            ChartOrders order = chartOrdersList.get(i);
            Row row = sheet.createRow(i + 1); // 从第二行开始填充数据
            row.createCell(0).setCellValue(order.getPhonenumber());
            row.createCell(1).setCellValue(order.getOrderNum());
            row.createCell(2).setCellValue(order.getOrderDetails());
            row.createCell(3).setCellValue(order.getCreateTime());
            row.createCell(4).setCellValue(order.getTotalPrice() / 100.0); // 转换为元
            row.createCell(5).setCellValue(order.getInvoiceStatus());
        }

        // 将工作簿写入字节输出流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        workbook.write(bos);
        workbook.close();
        bos.close();

        // 将字节输出流转换为字节数组
        byte[] bytes = bos.toByteArray();

        // 创建HTTP响应
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=orders.xlsx");
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        return ResponseEntity.ok()
                .headers(headers)
                .body(bytes);
    }





}

